package com.keyancompany.zhongbaopingtai.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.api.FileAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.DatePopupWindow;
import com.keyancompany.zhongbaopingtai.weight.MenuPopuWindow;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import com.photoselector.util.CommonUtils;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
import kankan.wheel.activity.CitiesActivity;

/**
 * 实名认证
 */
public class RealNameAutherActivity extends BaseActivity {

    private static final int RESULT_CODE = 1314;
    private final static int FRONT_CODE = 222;
    private final static int BEHIND_CODE = 223;
    private final static int ALL_CODE = 224;//手持证件照


    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.id_card_bettween)
    RadioButton idCardBettween;
    @Bind(R.id.id_card_always)
    RadioButton idCardAlways;
    @Bind(R.id.hadle_id_card)
    ImageView hadleIdCard;
    @Bind(R.id.front_id_card)
    ImageView frontIdCard;
    @Bind(R.id.behind_id_card)
    ImageView behindIdCard;
    @Bind(R.id.submit_auther)
    TextView submitAuther;
    @Bind(R.id.address)
    TextView address;
    @Bind(R.id.username_edit)
    EditText usernameEdit;
    @Bind(R.id.id_card_et)
    EditText idCardEt;
    @Bind(R.id.hadle_id_card_delete)
    ImageView hadleIdCardDelete;
    @Bind(R.id.hadle_id_card_progress)
    SmoothProgressBar hadleIdCardProgress;
    @Bind(R.id.hadle_id_card_upload_error)
    TextView hadleIdCardUploadError;
    @Bind(R.id.front_id_card_delete)
    ImageView frontIdCardDelete;
    @Bind(R.id.front_id_card_progress)
    SmoothProgressBar frontIdCardProgress;
    @Bind(R.id.front_id_card_upload_error)
    TextView frontIdCardUploadError;
    @Bind(R.id.behind_id_card_delete)
    ImageView behindIdCardDelete;
    @Bind(R.id.behind_id_card_progress)
    SmoothProgressBar behindIdCardProgress;
    @Bind(R.id.behind_id_card_upload_error)
    TextView behindIdCardUploadError;

    private Intent data;
    DatePopupWindow dpw;

    String province;
    String city;
    String district;
    private String[] papers_pic = new String[3];

    @Override
    protected int getContentViewId() {
        return R.layout.activity_real_name_auther;
    }

    @Override
    protected int getMenuId() {
        return 0;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, "实名认证");

    }

    @Override
    protected void setUpViews() {
        idCardBettween.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (dpw == null) {
                    dpw = new DatePopupWindow(RealNameAutherActivity.this);
                    dpw.setDateListener(new DatePopupWindow.IOnSelectDateListener() {
                        @Override
                        public void selectDate(int year, int moth, int day) {
                            idCardBettween.setText(year + "年" + (moth < 10 ? "0" + (moth + 1) : (moth + 1)) + "月" + (day < 10 ? "0" + day : day) + "日");
                        }
                    });
                }
                dpw.showAtLocation(idCardBettween, Gravity.CENTER, 0, 0);
            }
        });
    }


    @OnClick(R.id.submit_auther) //提交
    public void ToPayPassword(View view) {
        String name = usernameEdit.getText().toString();
        if (TextUtils.isEmpty(name)) {
            T.show(this, "请输入真实姓名", Toast.LENGTH_SHORT);
            return;
        }
        String idCard = idCardEt.getText().toString();
        if (TextUtils.isEmpty(idCard) || idCard.length() < 17) {
            T.show(this, "请输入正确的身份证号 17-18位", Toast.LENGTH_SHORT);
            return;
        }
        String addressStr = address.getText().toString();
        if (TextUtils.isEmpty(province)) {
            T.show(this, "请选择地址", Toast.LENGTH_SHORT);
            return;
        }
        if (validatePic()) {
            T.show(this, "请确认图片上传完毕 !", Toast.LENGTH_SHORT);
            return;
        }
        UserAPI.attestation(name, idCard, province, city, district, papersValue, addressStr, this, getLoading(-1));
    }

    String papersValue;

    private boolean validatePic() {
        papersValue = "{";
        for (int i = 0; i < papers_pic.length; i++) {
            if (TextUtils.isEmpty(papers_pic[i])) {
                return true;
            }
            papersValue += papers_pic[i];
            if (i != papers_pic.length - 1) {
                papersValue += ",";
            }
        }
        papersValue += "}";
        return false;
    }

    @OnClick(R.id.address)
    public void addressSelect(View view) {
        CitiesActivity.buildIntent(this, data, RESULT_CODE);
    }

    @OnClick(R.id.hadle_id_card) //手持证件
    public void selecAllPhoto(View view) {
        if (hadleIdCardProgress.getVisibility() == View.VISIBLE || hadleIdCardDelete.getVisibility() == View.VISIBLE) {
            return;
        }
        CommonUtils.launchActivityForResult(this,
                PhotoSelectorActivity.class, ALL_CODE, 1);
    }

    @OnClick(R.id.front_id_card) //证件前面
    public void selectForntPhoto(View view) {
        if (frontIdCardProgress.getVisibility() == View.VISIBLE || frontIdCardDelete.getVisibility() == View.VISIBLE) {
            return;
        }
        CommonUtils.launchActivityForResult(this,
                PhotoSelectorActivity.class, FRONT_CODE, 1);
    }


    @OnClick(R.id.behind_id_card) //证件背面
    public void selectBehindPhoto(View view) {
        if (behindIdCardProgress.getVisibility() == View.VISIBLE || behindIdCardDelete.getVisibility() == View.VISIBLE) {
            return;
        }
        CommonUtils.launchActivityForResult(this,
                PhotoSelectorActivity.class, BEHIND_CODE, 1);
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        BaseModel base = JSONObject.parseObject(json, BaseModel.class);
        if (base.isSuccess()) {
            finish();
        } else {
            T.showShort(RealNameAutherActivity.this, base.msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CODE && resultCode == RESULT_OK) {
            this.data = data;
            province = data.getStringExtra("provinceName");
            city = data.getStringExtra("cityName");
            district = data.getStringExtra("areaName");
            address.setText(province + "、" + city + "、" + district);
        }
        if (resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {

                if (requestCode == FRONT_CODE) {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras()
                            .getSerializable("photos");
                    if (photos == null || photos.isEmpty())
                        return;
                    ImageLoader.getInstance().displayImage("file:///" + photos.get(0).getOriginalPath(), frontIdCard);
                    uploadFile(0, frontIdCard, new File(photos.get(0).getOriginalPath()), frontIdCardDelete, frontIdCardProgress, frontIdCardUploadError);
                } else if (requestCode == BEHIND_CODE) {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras()
                            .getSerializable("photos");
                    if (photos == null || photos.isEmpty())
                        return;
                    ImageLoader.getInstance().displayImage("file:///" + photos.get(0).getOriginalPath(), behindIdCard);
                    uploadFile(1, behindIdCard, new File(photos.get(0).getOriginalPath()), behindIdCardDelete, behindIdCardProgress, behindIdCardUploadError);
                } else {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras()
                            .getSerializable("photos");
                    if (photos == null || photos.isEmpty())
                        return;
                    ImageLoader.getInstance().displayImage("file:///" + photos.get(0).getOriginalPath(), hadleIdCard);
                    uploadFile(2, hadleIdCard, new File(photos.get(0).getOriginalPath()), hadleIdCardDelete, hadleIdCardProgress, hadleIdCardUploadError);
                }
            }
        }
    }

    public void uploadFile(final int position, final ImageView iv, final File file, final ImageView delete, final SmoothProgressBar progressBar, final TextView uploadError) {
        uploadError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FileAPI.uploadFile(file, new FileIAsyncHttpResponseHandler(position, delete, progressBar, uploadError), null);
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                iv.setImageResource(R.mipmap.ic_auth_weixin);
                delete.setVisibility(View.GONE);
                uploadError.setVisibility(View.GONE);
                progressBar.setVisibility(View.GONE);
                papers_pic[position] = null;
            }
        });
        FileAPI.uploadFile(file, new FileIAsyncHttpResponseHandler(position, delete, progressBar, uploadError), null);
    }


    public class FileIAsyncHttpResponseHandler implements IAsyncHttpResponseHandler {
        ImageView delete;
        SmoothProgressBar progressBar;
        TextView uploadError;
        int position;

        public FileIAsyncHttpResponseHandler(int position, ImageView delete, SmoothProgressBar progressBar, TextView uploadError) {
            this.delete = delete;
            this.progressBar = progressBar;
            this.uploadError = uploadError;
            this.position = position;
        }

        @Override
        public void start(int type) {
            progressBar.setVisibility(View.VISIBLE);
            delete.setVisibility(View.GONE);
            uploadError.setVisibility(View.GONE);
        }

        @Override
        public void success(int type, String json) {
            progressBar.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.VISIBLE);
            uploadError.setVisibility(View.GONE);

            BaseModel base = validateJson(json);
            if (base.isSuccess()) {
                JSONObject jsonObject = JSONObject.parseObject(base.data);
                papers_pic[position] = jsonObject.getString("pid");
            } else {

            }
        }

        @Override
        public void failed(String error) {
            uploadError.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.INVISIBLE);
            delete.setVisibility(View.VISIBLE);
        }

        @Override
        public void finish(int type) {

        }
    }
}
